package com.imau.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imau.common.R;
import com.imau.common.ResultCodeEnum;
import com.imau.entity.Student;
import com.imau.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Api(tags = "学生管理")
@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @ApiOperation("添加学生信息")
    @PostMapping
    public R save(@RequestBody Student student) {

        // 默认密码身份证后5位
        student.setPassword(DigestUtils.md5DigestAsHex(student.getIdNumber().substring(13).getBytes()));

        student.setRole(0);

        studentService.save(student);

        return R.success(ResultCodeEnum.SUCCESS, "保存学生信息成功");
    }

    @ApiOperation("删除学生信息")
    @DeleteMapping("/delete/{id}")
    public R deleteById(@PathVariable Long id) {

        studentService.removeById(id);

        return R.success(ResultCodeEnum.SUCCESS, "删除学生信息成功");
    }

    @ApiOperation("修改学生信息")
    @PutMapping
    public R update(@RequestBody Student student) {

        studentService.updateById(student);

        return R.success(ResultCodeEnum.SUCCESS, "修改学生信息成功");
    }

    @ApiOperation("分页查询用户||条件查询")
    @GetMapping("/information")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("参数信息：page:{},pageSize:{},name:{}", page, pageSize, name);

        // 分页构造器
        Page<Student> pageInfo = new Page<>(page, pageSize);

        // 条件构造器
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

        if (name != null) {
            queryWrapper.like(Student::getName, name);
        }

        // 分页查询
        studentService.page(pageInfo, queryWrapper);

        return R.success(pageInfo, ResultCodeEnum.SUCCESS);

    }

}
